package man4j;

import java.util.Vector;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.ItemCommandListener;
import javax.microedition.lcdui.ItemStateListener;

public abstract class AbstractEditTaskScreen extends Form implements CommandListener {
	private Command backCommand;
	
	private MainMIDlet mainMIDlet;
	
	public AbstractEditTaskScreen(MainMIDlet mainMIDlet, String title) {		
		super(title);
		
		this.mainMIDlet = mainMIDlet;
		
		backCommand = new Command("Back", Command.BACK, 1);
		
		addCommand(backCommand);
		
		setCommandListener(this);
		
		Task task = new Task();
		
		setItemStateListener(new ItemStateListener() {
			public void itemStateChanged(Item item) {
				Task t = (Task) item;
				
				if (!t.isDirty()) {
					configureTask(t);
					
					insert(0, new Task());
				}
			}
		});
		
		append(task);
	}
	
	protected void configureTask(Task t) {
		t.makeDirty();
		
		Vector commands = getTaskCommands();
		
		for (int i = 0; i < commands.size(); i++) {
			t.addCommand((Command) commands.elementAt(i));
		}
		
		t.setItemCommandListener(getTaskCommandListener());
		
		onTaskAdded(t);
	}
	
	public MainMIDlet getMainMIDlet() {
		return mainMIDlet;
	}

	public void commandAction(Command c, Displayable d) {
		if (c == backCommand) {
			onSave();
			
			Display.getDisplay(mainMIDlet).setCurrent(mainMIDlet.getMainScreen());
		}		
	}
	
	protected abstract void onSave();
	
	protected int getItemNum(Item item) {
		for (int i = 0; i < size(); i++) {
			if (item == get(i)) {
				return i;
			}
		}
		
		return -1;
	}
	
	public void loadTasks() {
		Vector tasks = TaskStore.loadTasks(getClass().getName());
		
		for (int i = 0; i < tasks.size(); i++) {
			Task t = (Task) tasks.elementAt(i);
			
			configureTask(t);
			append(t);
		}
	}
	
	protected void onTaskAdded(Task t) {/* empty */}
	
	protected abstract Vector getTaskCommands();
	
	protected abstract ItemCommandListener getTaskCommandListener();
}
